/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gidoo.owl2.viewer.panels;

import java.util.LinkedList;
import java.util.List;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;
import org.apache.wicket.model.Model;
import org.gidoo.owl2.backend.DatabaseError;
import org.gidoo.owl2.backend.DictionaryProvider;
import org.gidoo.owl2.viewer.session.OwlSession;

/**
 *
 * @author thomas
 */
public class ResultPanel extends Panel
{

  public ResultPanel(String wicketID, long docID, String searchTerm)
  {
    super(wicketID);

    List<Long> result = new LinkedList<Long>();
    final DictionaryProvider dp = ((OwlSession) getSession()).getDicProvider();

    if(docID == -1 || searchTerm == null)
    {
      add(new Label("lblSearchTerm", "no search term yet"));
    }
    else
    {
      try
      {
        result = dp.getSearchResult(docID, searchTerm);
      }
      catch(DatabaseError ex)
      {
        error("Database error: " + ex.getMessage());
      }
      add(new Label("lblSearchTerm", new Model<String>("" + result.size() + " "
        + (result.size() == 1 ? "result" : "results") + " for \"" + searchTerm + "\"")));

    }

    DataView<Long> lsvResults = new DataView<Long>("lsvResults",
      new ListDataProvider<Long>(result))
    {

      @Override
      protected void populateItem(Item<Long> item)
      {
        // get source code
        String src = "database error";
        try
        {
          src = dp.getXMLSource(item.getModelObject());
        }
        catch(DatabaseError ex)
        {
          error("Database error: " + ex.getMessage());
        }
        item.add(new Label("lblResultCode", new Model<String>(src)));
      }
    };
    lsvResults.setItemsPerPage(5);
    add(lsvResults);

    PagingNavigator pager = new PagingNavigator("pager", lsvResults);
    pager.setVisible(result.size() > 5);
    add(pager);
  }
}
